﻿using Anley.DomainDrivenDesign.Contract.Enums;

namespace Anley.DomainDrivenDesign.Contract.Application;

/// <summary>
/// 结果类
/// </summary>
public class AneResult : IActionResult
{
    protected readonly static JsonSerializerSettings _jsonSerializerSettings;

    static AneResult()
    {
        _jsonSerializerSettings = new JsonSerializerSettings();
        _jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();    // 驼峰式命名
        _jsonSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;               // 忽略循环引用
        _jsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore;                       // 空值处理
        _jsonSerializerSettings.Formatting = Formatting.Indented;                                   // 自动缩进
        _jsonSerializerSettings.DateFormatString = AneConsts.DefaultDateTimeFormat;                 // 日期时间格式
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="code">状态码</param>
    /// <param name="message">消息</param>
    public AneResult(
        int code,
        string message)
    {
        Code = code;
        Message = message;
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="code">状态码</param>
    public AneResult(
        int code)
        : this(code, string.Empty)
    {
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="code">状态码</param>
    public AneResult(
        AneResultCode code)
        : this((int)code)
    {
    }

    /// <summary>
    /// 状态码
    /// </summary>
    public int Code { get; protected set; }

    /// <summary>
    /// 消息
    /// </summary>
    public string Message { get; protected set; }

    /// <summary>
    /// 成功
    /// </summary>
    public static AneResult Ok()
    {
        return new AneResult((int)AneResultCode.Success);
    }

    /// <summary>
    /// 失败
    /// </summary>
    /// <param name="message">消息</param>
    public static AneResult Fail(
        string message)
    {
        return new AneResult((int)AneResultCode.Fail, message);
    }

    /// <summary>
    /// 错误
    /// </summary>
    /// <param name="code">状态码</param>
    /// <param name="message">消息</param>
    public static AneResult Error(
        AneResultCode code,
        string message)
    {
        return new AneResult((int)code, message);
    }

    /// <summary>
    /// 执行结果
    /// </summary>
    /// <param name="context"></param>
    public Task ExecuteResultAsync(ActionContext context)
    {
        context.HttpContext.Response.ContentType = AneConsts.JSONContentType;
        var jsonString = JsonConvert.SerializeObject(this, _jsonSerializerSettings);
        return context.HttpContext.Response.WriteAsync(jsonString);
    }

    public static implicit operator bool(AneResult result)
    {
        return result.Code == (int)AneResultCode.Success;
    }
}